import GameData from "../Data/GameData";
import GameManager from "../Managers/GameManager";

const {ccclass, property} = cc._decorator;

@ccclass
export default class Nail extends cc.Component {

    joints:cc.RevoluteJoint[];
    // LIFE-CYCLE CALLBACKS:

    // onLoad () {}

    start () {
        this.joints = this.node.getComponents(cc.RevoluteJoint);
        this.joints.forEach(joint => {
            if(joint.enabled && joint.connectedBody){
                var wood = joint.connectedBody.node;
                var worldPos = cc.v2(this.node.parent.convertToWorldSpaceAR(this.node.position));
                var distance:number;
                var target:number;
                for (var i = 0; i < wood.children.length; i++) {
                    var woodHole = wood.children[i];
                    var holePos = cc.v2(wood.convertToWorldSpaceAR(woodHole.position));
                    var dis = cc.Vec2.distance(worldPos, holePos);
                    if(i == 0 || distance > dis) {
                        distance = dis;
                        target = i;
                    }
                }
                joint.connectedAnchor = cc.Vec2.multiplyScalar(joint.connectedAnchor, cc.v2(wood.children[target].position), GameData.scales[GameManager.Instance.levelNum]);
                joint.apply();
            }
        });
    }

    // update (dt) {}
}
